package com.hzncc.scaffold.core;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

/**
 * @author lqs
 * http请求日志打印
 * @date 2021/11/6
 */
@Aspect
@Component
public class WebLogAspect {

  private static final Logger LOG = LoggerFactory.getLogger(WebLogAspect.class);
  private final ObjectMapper mapper;

  public WebLogAspect(ObjectMapper mapper) {
    this.mapper = mapper;
  }

  /**
   * 以 controller 包下定义的所有请求为切入点
   */
  @Pointcut("execution(public * com.hzncc.scaffold.handler..*.*(..))")
  public void webLog() {
  }

  /**
   * 在切点之前织入
   *
   * @param joinPoint
   * @throws Throwable
   */
  @Before("webLog()")
  public void doBefore(JoinPoint joinPoint) {
    // 开始打印请求日志
    ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
    HttpServletRequest request = Objects.requireNonNull(attributes).getRequest();
    LOG.info("========================================== Start ==========================================");
    LOG.info("Request URL    : {}", request.getRequestURL().toString());
    LOG.info("HTTP Method    : {}", request.getMethod());
    LOG.info("Class Method   : {}.{}", joinPoint.getSignature().getDeclaringTypeName(), joinPoint.getSignature().getName());
    LOG.info("IP Address     : {}", request.getRemoteAddr());
    try {
      LOG.info("Request Args   : {}", mapper.writeValueAsString(joinPoint.getArgs()));
    } catch (JsonProcessingException e) {
      LOG.info("Request Args   : args can not be printed");
    }

  }

  /**
   * 在切点之后织入
   */
  @After("webLog()")
  public void doAfter() {
    LOG.info("=========================================== End ===========================================");
    // 每个请求之间空一行
    LOG.info(StringUtils.EMPTY);
  }

  /**
   * 环绕
   *
   * @param proceedingJoinPoint
   * @return
   * @throws Throwable
   */
  @Around("webLog()")
  public Object doAround(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
    long startTime = System.currentTimeMillis();
    Object result = proceedingJoinPoint.proceed();
    try {
      LOG.info("Response Args  : {}", mapper.writeValueAsString(result));
    } catch (JsonProcessingException e) {
      LOG.info("Response       : result can not be printed");
    }
    // 打印出参
    // 执行耗时
    long consume = System.currentTimeMillis() - startTime;
    LOG.info("Time-Consuming : {} ms", consume);
    /**
     * 超过timeLimit发出警告
     */
    long timeLimit = 1500;
    if (consume > timeLimit) {
      LOG.warn("API执行时间过长......");
    }
    return result;
  }

}
